package com.bjfu.educenter.controller;


import com.bjfu.common_utils.JwtUtils;
import com.bjfu.common_utils.R;
import com.bjfu.common_utils.vo.UcenterMemberVo;
import com.bjfu.educenter.entity.UcenterMember;
import com.bjfu.educenter.entity.vo.RegisterVo;
import com.bjfu.educenter.service.UcenterMemberService;
import com.bjfu.servicebase.exceptionhandler.GuliException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 会员表 前端控制器
 * </p>
 *
 * @author Guli
 * @since 2020-07-13
 */
@RestController
@RequestMapping("/educenter/member")
//@CrossOrigin
@Api(tags = "用户中心")
public class UcenterMemberController {
    @Autowired
    private UcenterMemberService memberService;

    // 登录
    @PostMapping("login")
    public R loginUser(
            @RequestBody UcenterMember member
    ){
        // 调用service方法实现登录
        // 返回token值，使用jwt生成
        String token = memberService.login(member);
        return R.ok().data("token",token);
    }

    // 注册
    @PostMapping("register")
    public R registerUser(
            @RequestBody RegisterVo registerVo
    ){
        memberService.register(registerVo);
        return R.ok();
    }

    //获取token中用户信息
    @GetMapping("getLoginInfo")
    public R getLoginInfo(HttpServletRequest request){
        try {
            // 调用jwt工具类，根据request对象获取头信息，返回用户id
            String memberId = JwtUtils.getMemberIdByJwtToken(request);
            // 查询用户信息
            UcenterMember member = memberService.getById(memberId);
            return R.ok().data("userInfo",member);
        } catch (Exception e) {
            e.printStackTrace();
            throw new GuliException(20001,"获取用户信息失败");
        }
    }

    @ApiOperation("根据用户id获取用户信息")
    @GetMapping("getMemberInfo/{id}")
    public UcenterMemberVo getMemberInfo(@PathVariable String id){
        UcenterMemberVo ucenterMemberVo = new UcenterMemberVo();
        UcenterMember member = memberService.getById(id);
        BeanUtils.copyProperties(member,ucenterMemberVo);
        return ucenterMemberVo;
    }

    @GetMapping("countRegister/{day}")
    public R countRegister(@PathVariable String day){
        Integer count = memberService.countRegisterDay(day);
        return R.ok().data("countRegister",count);
    }


}

